import axios from 'axios';
import {queryString} from './util.js'
import {
  Toast
} from 'vant'


// 引用axios，设置头文件
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';

//请求返回拦截，把数据返回到页面之前做些什么...
axios.interceptors.response.use((res) => {
  

  if(res.data.a == 0 || res.data.IMG_PRE) {
    return Promise.resolve(res.data);
  } else {

    if(res.data.c) {
      Toast({
        message: res.data.c,
        duration: 3000
      })
    }
    return Promise.reject(res.data);
  }


}, function (error) {
  console.log(error)
  Toast.clear()
  if(error.message) {
    Toast(error.message)
  }
  return Promise.reject(
    error
  );
});

function apiAxios(method, url, params, token) {
  token = token ? token : (localStorage.getItem('token') ? localStorage.getItem('token') : '')
  params = params ? params : {}
  let baseURL = 'getUserName/'
  if(url) {
    params.reqUrl = url
  }

  if(params.isMd5) { // md5 加密传参
   
  }
 
  let result = queryString(baseURL, params)
  console.log(result)
  let str = []
  for (let key in params) {
    str.push(key + '=' + params[key])
  }
  let paramStr = str.join('&')
  
 


  return axios({
    method: method,
    //拼接参数
    url: method === 'GET' || method === 'DELETE' ? baseURL + paramStr : baseURL,
    data: params,
    // baseURL: baseURL,
    timeout: 10000,
    headers: {
      ACCESS_TOKEN: token,
    },
    withCredentials: false
  })
}

export default {
  get: function (url, params, token) {
    return apiAxios('GET', url, params, token)
  },
  post: function (url, params, token) {
    return apiAxios('POST', url, params, token)
  },
  put: function (url, params, token) {
    return apiAxios('PUT', url, params, token)
  },
  delete: function (url, params, token) {
    return apiAxios('DELETE', url, params, token)
  },
}